package com.woniushop.web.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woniushop.entity.OrderForm;
import com.woniushop.entity.OrderInfo;
import com.woniushop.entity.User;
import com.woniushop.service.GoodsService;
import com.woniushop.service.OrderFormService;
import com.woniushop.service.OrderInfoService;
import com.woniushop.service.imple.GoodsServiceImple;
import com.woniushop.service.imple.OrderFormServiceImple;
import com.woniushop.service.imple.OrderInfoServiceImple;
import com.woniushop.utils.ControllerUtils;

/**
 * Servlet implementation class OrderFormServlet
 */
@WebServlet("/orderInfo")
public class OrderInfoServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private OrderInfoService orderInfoService = new OrderInfoServiceImple();
	private GoodsService goodsService = new GoodsServiceImple();
	private OrderFormService orderFormService = new OrderFormServiceImple();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		switch (opr) {
		case "addCartInfo":// 添加购物车信息
			addCartInfo(request, response);
			break;
		case "findAllCart":// 找到当前用户所有购物车信息
			findAllCart(request, response);
			break;
		case "changeOium":// 修改订单明细中商品数量
			changeOium(request, response);
			break;
		case "delAll":// 删除订单明细
			delAll(request, response);
			break;
		case "showInfo":// 删除订单明细
			showInfo(request, response);
			break;
		default:

			break;
		}
	}

	private void showInfo(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2) {
				request.setAttribute("msg", "null");
			} else {
				Integer oid = Integer.parseInt(request.getParameter("oid"));
				OrderForm orderForm = orderFormService.findOne(oid);
				List<OrderInfo> list = orderInfoService.findAll(oid);
				// 计算商品总价
				BigDecimal totalPrice = new BigDecimal(0);
				for (OrderInfo orderInfo : list) {
					BigDecimal num = new BigDecimal(orderInfo.getOinum());
					totalPrice = totalPrice.add(orderInfo.getGprice().multiply(num));
				}
				// 将订单、订单明细、商品总价发往支付页面
				map.put("msg", "ok");
				request.getSession().setAttribute("orderForm", orderForm);
				request.getSession().setAttribute("list", list);
				request.getSession().setAttribute("totalPrice", totalPrice);
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 删除订单明细
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	private void delAll(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				// 读取订单明细id
				String[] oiids = request.getParameterValues("oiids[]");
				orderInfoService.delAll(oiids);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 修改订单明细中商品数量
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	private void changeOium(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				// 读取订单明细id和商品数量
				Integer oiid = Integer.parseInt(request.getParameter("oiid"));
				Integer oinum = Integer.parseInt(request.getParameter("oinum"));

				OrderInfo orderInfo = orderInfoService.finOne(oiid);
				if (orderInfo.getOid().equals(loginUser.getUcartid())) {
					Integer gstock = orderInfo.getGstock();

					oinum = oinum > gstock ? gstock : oinum;
					oinum = oinum > 999 ? 999 : oinum;
					oinum = oinum < 1 ? 1 : oinum;

					orderInfo.setOinum(oinum);
					orderInfoService.update(orderInfo);
					map.put("orderInfo", orderInfo);
					if (oinum > gstock) {
						map.put("msg", "outnum");
					} else {
						map.put("msg", "ok");
					}
				} else {
					map.put("msg", "null");
				}
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 找到当前用户所有购物车信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 */
	private void findAllCart(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				// 获得所有数据
				List<OrderInfo> list = orderInfoService.findAll(loginUser.getUcartid());
				map.put("list", list);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 添加购物车信息
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void addCartInfo(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				// 获得订单详情对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				OrderInfo orderInfo = (OrderInfo) ControllerUtils.mapToObject(parameterMap, OrderInfo.class);

				// 没有传入数量则将数量改为1
				if (orderInfo.getOinum() == null) {
					orderInfo.setOinum(1);
				}

				// 设置购物车订单id
				Integer ucartid = loginUser.getUcartid();
				orderInfo.setOid(ucartid);

				// 设置订单明细商品价格
				BigDecimal oiprice = goodsService.getPriceByGid(orderInfo.getGid());
				orderInfo.setOiprice(oiprice);

				orderInfoService.add(orderInfo);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
